import React, { useState, useCallback } from 'react'
import { 
  User, Mail, Bell, Shield, CreditCard, Settings, 
  Save, X, Eye, EyeOff, AlertCircle, CheckCircle,
  Download, Trash2, RefreshCw
} from 'lucide-react'
import { useAuth, useUserProfile, useSubscription } from '../../contexts/AuthProvider'
import { ChangePasswordFormData, UpdateProfileFormData, ArxivCategory } from '../../types/auth'

interface UserProfileProps {
  isOpen: boolean
  onClose: () => void
  defaultTab?: 'profile' | 'preferences' | 'notifications' | 'privacy' | 'subscription' | 'security'
}

const ARXIV_CATEGORIES: { value: ArxivCategory; label: string }[] = [
  { value: 'cs.AI', label: 'Artificial Intelligence' },
  { value: 'cs.CL', label: 'Computation and Language' },
  { value: 'cs.CV', label: 'Computer Vision' },
  { value: 'cs.LG', label: 'Machine Learning' },
  { value: 'cs.NE', label: 'Neural and Evolutionary Computing' },
  { value: 'cs.RO', label: 'Robotics' },
  { value: 'math.AG', label: 'Algebraic Geometry' },
  { value: 'math.AT', label: 'Algebraic Topology' },
  { value: 'math.CO', label: 'Combinatorics' },
  { value: 'physics.app-ph', label: 'Applied Physics' },
  { value: 'physics.atom-ph', label: 'Atomic Physics' },
  { value: 'stat.ML', label: 'Machine Learning (Statistics)' }
]

export function UserProfile({ isOpen, onClose, defaultTab = 'profile' }: UserProfileProps) {
  const [activeTab, setActiveTab] = useState(defaultTab)
  const [loading, setLoading] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [success, setSuccess] = useState<Record<string, boolean>>({})
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [showNewPassword, setShowNewPassword] = useState(false)

  const { user, updateProfile, updatePassword, deleteAccount, signOut } = useAuth()
  const { userProfile, updatePreferences, hasGdprConsent } = useUserProfile()
  const { subscription, planType } = useSubscription()

  // Form states
  const [profileData, setProfileData] = useState<UpdateProfileFormData>({
    full_name: userProfile?.full_name || '',
    display_name: userProfile?.display_name || '',
    avatar_url: userProfile?.avatar_url || '',
    phone_number: userProfile?.phone_number || ''
  })

  const [passwordData, setPasswordData] = useState<ChangePasswordFormData>({
    currentPassword: '',
    newPassword: '',
    confirmNewPassword: ''
  })

  const [selectedCategories, setSelectedCategories] = useState<ArxivCategory[]>(
    userProfile?.paper_preferences.categories || []
  )

  const [keywords, setKeywords] = useState<string>(
    userProfile?.paper_preferences.keywords.join(', ') || ''
  )

  const [notificationSettings, setNotificationSettings] = useState(
    userProfile?.notification_preferences || {
      email_notifications: true,
      weekly_digest: false,
      instant_alerts: false,
      paper_recommendations: true,
      new_category_papers: false,
      author_updates: false,
      keyword_matches: false,
      push_notifications: false,
      sms_notifications: false,
      digest_frequency: 'weekly',
      quiet_hours: {
        enabled: false,
        start_time: '22:00',
        end_time: '08:00'
      }
    }
  )

  const [privacySettings, setPrivacySettings] = useState(
    userProfile?.privacy_settings || {
      profile_visibility: 'private',
      search_history_retention: 30,
      data_sharing_consent: false,
      analytics_consent: false,
      marketing_consent: false,
      research_participation_consent: false,
      data_export_format: 'json'
    }
  )

  // Clear success messages after delay
  const showSuccess = useCallback((key: string) => {
    setSuccess(prev => ({ ...prev, [key]: true }))
    setTimeout(() => {
      setSuccess(prev => ({ ...prev, [key]: false }))
    }, 3000)
  }, [])

  // Update profile information
  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setErrors({})

    try {
      await updateProfile(profileData)
      showSuccess('profile')
    } catch (error: any) {
      setErrors({ profile: error.message })
    } finally {
      setLoading(false)
    }
  }

  // Change password
  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault()
    const newErrors: Record<string, string> = {}

    if (!passwordData.currentPassword) {
      newErrors.currentPassword = 'Current password is required'
    }

    if (!passwordData.newPassword) {
      newErrors.newPassword = 'New password is required'
    } else if (passwordData.newPassword.length < 8) {
      newErrors.newPassword = 'Password must be at least 8 characters'
    }

    if (passwordData.newPassword !== passwordData.confirmNewPassword) {
      newErrors.confirmNewPassword = 'Passwords do not match'
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors)
      return
    }

    setLoading(true)
    setErrors({})

    try {
      await updatePassword(passwordData.newPassword)
      setPasswordData({
        currentPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      })
      showSuccess('password')
    } catch (error: any) {
      setErrors({ password: error.message })
    } finally {
      setLoading(false)
    }
  }

  // Update paper preferences
  const handleUpdatePaperPreferences = async () => {
    setLoading(true)
    setErrors({})

    try {
      await updatePreferences('paper', {
        categories: selectedCategories,
        keywords: keywords.split(',').map(k => k.trim()).filter(k => k),
        authors: userProfile?.paper_preferences.authors || [],
        institutions: userProfile?.paper_preferences.institutions || []
      })
      showSuccess('preferences')
    } catch (error: any) {
      setErrors({ preferences: error.message })
    } finally {
      setLoading(false)
    }
  }

  // Update notification preferences
  const handleUpdateNotifications = async () => {
    setLoading(true)
    setErrors({})

    try {
      await updatePreferences('notification', notificationSettings)
      showSuccess('notifications')
    } catch (error: any) {
      setErrors({ notifications: error.message })
    } finally {
      setLoading(false)
    }
  }

  // Update privacy settings
  const handleUpdatePrivacy = async () => {
    setLoading(true)
    setErrors({})

    try {
      await updatePreferences('privacy', privacySettings)
      showSuccess('privacy')
    } catch (error: any) {
      setErrors({ privacy: error.message })
    } finally {
      setLoading(false)
    }
  }

  // Export user data (GDPR compliance)
  const handleExportData = async () => {
    // Implementation would generate and download user data
    console.log('Exporting user data...')
  }

  // Delete account
  const handleDeleteAccount = async () => {
    if (window.confirm('Are you sure you want to delete your account? This action cannot be undone.')) {
      setLoading(true)
      try {
        await deleteAccount()
        onClose()
      } catch (error: any) {
        setErrors({ delete: error.message })
        setLoading(false)
      }
    }
  }

  if (!isOpen || !userProfile) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg w-full max-w-4xl mx-4 max-h-[90vh] overflow-hidden">
        <div className="flex justify-between items-center p-6 border-b">
          <h2 className="text-2xl font-bold text-gray-800">Account Settings</h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X size={24} />
          </button>
        </div>

        <div className="flex h-full">
          {/* Sidebar Navigation */}
          <div className="w-64 bg-gray-50 border-r p-4 space-y-2">
            {[
              { key: 'profile', label: 'Profile', icon: User },
              { key: 'preferences', label: 'Paper Preferences', icon: Settings },
              { key: 'notifications', label: 'Notifications', icon: Bell },
              { key: 'privacy', label: 'Privacy & Data', icon: Shield },
              { key: 'subscription', label: 'Subscription', icon: CreditCard },
              { key: 'security', label: 'Security', icon: Shield }
            ].map(({ key, label, icon: Icon }) => (
              <button
                key={key}
                onClick={() => setActiveTab(key as any)}
                className={`w-full flex items-center px-4 py-2 text-left rounded-md transition-colors ${
                  activeTab === key
                    ? 'bg-blue-100 text-blue-700 border border-blue-200'
                    : 'text-gray-600 hover:bg-gray-100'
                }`}
              >
                <Icon size={18} className="mr-3" />
                {label}
              </button>
            ))}
          </div>

          {/* Content Area */}
          <div className="flex-1 p-6 overflow-y-auto">
            {/* Profile Tab */}
            {activeTab === 'profile' && (
              <div>
                <h3 className="text-lg font-semibold mb-4">Profile Information</h3>
                
                {success.profile && (
                  <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-md flex items-center">
                    <CheckCircle className="text-green-500 mr-2" size={18} />
                    <p className="text-green-700 text-sm">Profile updated successfully!</p>
                  </div>
                )}

                {errors.profile && (
                  <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md flex items-center">
                    <AlertCircle className="text-red-500 mr-2" size={18} />
                    <p className="text-red-600 text-sm">{errors.profile}</p>
                  </div>
                )}

                <form onSubmit={handleUpdateProfile} className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Full Name
                    </label>
                    <input
                      type="text"
                      value={profileData.full_name}
                      onChange={(e) => setProfileData(prev => ({ ...prev, full_name: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Display Name
                    </label>
                    <input
                      type="text"
                      value={profileData.display_name}
                      onChange={(e) => setProfileData(prev => ({ ...prev, display_name: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Email Address
                    </label>
                    <input
                      type="email"
                      value={user?.email || ''}
                      disabled
                      className="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50 text-gray-500"
                    />
                    <p className="text-xs text-gray-500 mt-1">Email cannot be changed here. Contact support if needed.</p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Phone Number (optional)
                    </label>
                    <input
                      type="tel"
                      value={profileData.phone_number}
                      onChange={(e) => setProfileData(prev => ({ ...prev, phone_number: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <button
                    type="submit"
                    disabled={loading}
                    className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
                  >
                    <Save size={18} className="mr-2" />
                    {loading ? 'Saving...' : 'Save Changes'}
                  </button>
                </form>
              </div>
            )}

            {/* Paper Preferences Tab */}
            {activeTab === 'preferences' && (
              <div>
                <h3 className="text-lg font-semibold mb-4">Paper Preferences</h3>
                
                {success.preferences && (
                  <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-md flex items-center">
                    <CheckCircle className="text-green-500 mr-2" size={18} />
                    <p className="text-green-700 text-sm">Preferences updated successfully!</p>
                  </div>
                )}

                <div className="space-y-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      ArXiv Categories
                    </label>
                    <div className="grid grid-cols-2 gap-2 max-h-60 overflow-y-auto border border-gray-300 rounded-md p-3">
                      {ARXIV_CATEGORIES.map(category => (
                        <label key={category.value} className="flex items-center">
                          <input
                            type="checkbox"
                            checked={selectedCategories.includes(category.value)}
                            onChange={(e) => {
                              if (e.target.checked) {
                                setSelectedCategories(prev => [...prev, category.value])
                              } else {
                                setSelectedCategories(prev => prev.filter(c => c !== category.value))
                              }
                            }}
                            className="mr-2"
                          />
                          <span className="text-sm">{category.label}</span>
                        </label>
                      ))}
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Keywords (comma-separated)
                    </label>
                    <textarea
                      value={keywords}
                      onChange={(e) => setKeywords(e.target.value)}
                      placeholder="machine learning, neural networks, artificial intelligence"
                      rows={3}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <button
                    onClick={handleUpdatePaperPreferences}
                    disabled={loading}
                    className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
                  >
                    <Save size={18} className="mr-2" />
                    {loading ? 'Saving...' : 'Save Preferences'}
                  </button>
                </div>
              </div>
            )}

            {/* Notifications Tab */}
            {activeTab === 'notifications' && (
              <div>
                <h3 className="text-lg font-semibold mb-4">Notification Settings</h3>
                
                {success.notifications && (
                  <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-md flex items-center">
                    <CheckCircle className="text-green-500 mr-2" size={18} />
                    <p className="text-green-700 text-sm">Notification settings updated successfully!</p>
                  </div>
                )}

                <div className="space-y-4">
                  {[
                    { key: 'email_notifications', label: 'Email Notifications', description: 'Receive notifications via email' },
                    { key: 'weekly_digest', label: 'Weekly Digest', description: 'Summary of new papers in your areas of interest' },
                    { key: 'instant_alerts', label: 'Instant Alerts', description: 'Immediate notifications for high-priority matches' },
                    { key: 'paper_recommendations', label: 'Paper Recommendations', description: 'Personalized paper suggestions' },
                    { key: 'new_category_papers', label: 'New Category Papers', description: 'Notifications when new papers are published in your categories' },
                    { key: 'author_updates', label: 'Author Updates', description: 'Notifications when followed authors publish new papers' },
                    { key: 'keyword_matches', label: 'Keyword Matches', description: 'Notifications for papers matching your keywords' }
                  ].map(({ key, label, description }) => (
                    <div key={key} className="flex items-center justify-between">
                      <div>
                        <h4 className="font-medium text-gray-700">{label}</h4>
                        <p className="text-sm text-gray-500">{description}</p>
                      </div>
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={notificationSettings[key as keyof typeof notificationSettings] as boolean}
                          onChange={(e) => setNotificationSettings(prev => ({
                            ...prev,
                            [key]: e.target.checked
                          }))}
                          className="sr-only peer"
                        />
                        <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                      </label>
                    </div>
                  ))}

                  <div className="border-t pt-4">
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Digest Frequency
                    </label>
                    <select
                      value={notificationSettings.digest_frequency}
                      onChange={(e) => setNotificationSettings(prev => ({
                        ...prev,
                        digest_frequency: e.target.value as 'daily' | 'weekly' | 'monthly'
                      }))}
                      className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="daily">Daily</option>
                      <option value="weekly">Weekly</option>
                      <option value="monthly">Monthly</option>
                    </select>
                  </div>

                  <button
                    onClick={handleUpdateNotifications}
                    disabled={loading}
                    className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
                  >
                    <Save size={18} className="mr-2" />
                    {loading ? 'Saving...' : 'Save Notification Settings'}
                  </button>
                </div>
              </div>
            )}

            {/* Privacy Tab */}
            {activeTab === 'privacy' && (
              <div>
                <h3 className="text-lg font-semibold mb-4">Privacy & Data Settings</h3>
                
                {success.privacy && (
                  <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-md flex items-center">
                    <CheckCircle className="text-green-500 mr-2" size={18} />
                    <p className="text-green-700 text-sm">Privacy settings updated successfully!</p>
                  </div>
                )}

                <div className="space-y-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Profile Visibility
                    </label>
                    <select
                      value={privacySettings.profile_visibility}
                      onChange={(e) => setPrivacySettings(prev => ({
                        ...prev,
                        profile_visibility: e.target.value as 'public' | 'private' | 'academic'
                      }))}
                      className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="private">Private</option>
                      <option value="academic">Academic Community Only</option>
                      <option value="public">Public</option>
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Search History Retention (days)
                    </label>
                    <input
                      type="number"
                      value={privacySettings.search_history_retention}
                      onChange={(e) => setPrivacySettings(prev => ({
                        ...prev,
                        search_history_retention: parseInt(e.target.value)
                      }))}
                      min="0"
                      max="365"
                      className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div className="space-y-4">
                    {[
                      { key: 'data_sharing_consent', label: 'Data Sharing', description: 'Allow sharing anonymized data for research purposes' },
                      { key: 'analytics_consent', label: 'Analytics', description: 'Allow collection of usage analytics' },
                      { key: 'marketing_consent', label: 'Marketing', description: 'Receive marketing communications' },
                      { key: 'research_participation_consent', label: 'Research Participation', description: 'Participate in research studies' }
                    ].map(({ key, label, description }) => (
                      <div key={key} className="flex items-center justify-between">
                        <div>
                          <h4 className="font-medium text-gray-700">{label}</h4>
                          <p className="text-sm text-gray-500">{description}</p>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={privacySettings[key as keyof typeof privacySettings] as boolean}
                            onChange={(e) => setPrivacySettings(prev => ({
                              ...prev,
                              [key]: e.target.checked
                            }))}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                        </label>
                      </div>
                    ))}
                  </div>

                  <div className="border-t pt-4 space-y-4">
                    <h4 className="font-medium text-gray-700">Data Export & Deletion</h4>
                    
                    <div className="flex space-x-4">
                      <button
                        onClick={handleExportData}
                        className="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
                      >
                        <Download size={18} className="mr-2" />
                        Export My Data
                      </button>
                      
                      <button
                        onClick={handleDeleteAccount}
                        className="flex items-center px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
                      >
                        <Trash2 size={18} className="mr-2" />
                        Delete Account
                      </button>
                    </div>
                  </div>

                  <button
                    onClick={handleUpdatePrivacy}
                    disabled={loading}
                    className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
                  >
                    <Save size={18} className="mr-2" />
                    {loading ? 'Saving...' : 'Save Privacy Settings'}
                  </button>
                </div>
              </div>
            )}

            {/* Subscription Tab */}
            {activeTab === 'subscription' && (
              <div>
                <h3 className="text-lg font-semibold mb-4">Subscription Management</h3>
                
                <div className="bg-gray-50 rounded-lg p-4 mb-6">
                  <h4 className="font-medium text-gray-700 mb-2">Current Plan</h4>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-lg font-semibold capitalize">{planType} Plan</p>
                      <p className="text-sm text-gray-500">
                        {subscription?.status === 'active' ? 'Active' : 'Inactive'}
                        {subscription?.end_date && ` until ${new Date(subscription.end_date).toLocaleDateString()}`}
                      </p>
                    </div>
                    <button className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                      Upgrade Plan
                    </button>
                  </div>
                </div>

                {subscription && (
                  <div className="space-y-4">
                    <h4 className="font-medium text-gray-700">Plan Features</h4>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="border rounded-lg p-3">
                        <p className="font-medium">Saved Papers</p>
                        <p className="text-sm text-gray-500">
                          {subscription.features.max_saved_papers === -1 
                            ? 'Unlimited' 
                            : `${subscription.usage_metrics?.saved_papers_count || 0} / ${subscription.features.max_saved_papers}`
                          }
                        </p>
                      </div>
                      <div className="border rounded-lg p-3">
                        <p className="font-medium">Active Alerts</p>
                        <p className="text-sm text-gray-500">
                          {subscription.features.max_alerts === -1 
                            ? 'Unlimited' 
                            : `${subscription.usage_metrics?.active_alerts_count || 0} / ${subscription.features.max_alerts}`
                          }
                        </p>
                      </div>
                      <div className="border rounded-lg p-3">
                        <p className="font-medium">API Access</p>
                        <p className="text-sm text-gray-500">
                          {subscription.features.api_access ? 'Enabled' : 'Disabled'}
                        </p>
                      </div>
                      <div className="border rounded-lg p-3">
                        <p className="font-medium">Advanced Search</p>
                        <p className="text-sm text-gray-500">
                          {subscription.features.advanced_search ? 'Enabled' : 'Disabled'}
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* Security Tab */}
            {activeTab === 'security' && (
              <div>
                <h3 className="text-lg font-semibold mb-4">Security Settings</h3>
                
                {success.password && (
                  <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-md flex items-center">
                    <CheckCircle className="text-green-500 mr-2" size={18} />
                    <p className="text-green-700 text-sm">Password changed successfully!</p>
                  </div>
                )}

                {errors.password && (
                  <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md flex items-center">
                    <AlertCircle className="text-red-500 mr-2" size={18} />
                    <p className="text-red-600 text-sm">{errors.password}</p>
                  </div>
                )}

                <form onSubmit={handleChangePassword} className="space-y-4 mb-8">
                  <h4 className="font-medium text-gray-700">Change Password</h4>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Current Password
                    </label>
                    <div className="relative">
                      <input
                        type={showCurrentPassword ? 'text' : 'password'}
                        value={passwordData.currentPassword}
                        onChange={(e) => setPasswordData(prev => ({ ...prev, currentPassword: e.target.value }))}
                        className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        type="button"
                        onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                      >
                        {showCurrentPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                      </button>
                    </div>
                    {errors.currentPassword && <p className="text-red-600 text-sm mt-1">{errors.currentPassword}</p>}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      New Password
                    </label>
                    <div className="relative">
                      <input
                        type={showNewPassword ? 'text' : 'password'}
                        value={passwordData.newPassword}
                        onChange={(e) => setPasswordData(prev => ({ ...prev, newPassword: e.target.value }))}
                        className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        type="button"
                        onClick={() => setShowNewPassword(!showNewPassword)}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                      >
                        {showNewPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                      </button>
                    </div>
                    {errors.newPassword && <p className="text-red-600 text-sm mt-1">{errors.newPassword}</p>}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Confirm New Password
                    </label>
                    <input
                      type="password"
                      value={passwordData.confirmNewPassword}
                      onChange={(e) => setPasswordData(prev => ({ ...prev, confirmNewPassword: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                    {errors.confirmNewPassword && <p className="text-red-600 text-sm mt-1">{errors.confirmNewPassword}</p>}
                  </div>

                  <button
                    type="submit"
                    disabled={loading}
                    className="flex items-center px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50"
                  >
                    <RefreshCw size={18} className="mr-2" />
                    {loading ? 'Changing...' : 'Change Password'}
                  </button>
                </form>

                <div className="border-t pt-6">
                  <h4 className="font-medium text-gray-700 mb-4">Account Actions</h4>
                  <div className="space-y-2">
                    <button
                      onClick={() => signOut()}
                      className="flex items-center px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700"
                    >
                      Sign Out All Devices
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}